<template>
    <teleport to="body">
        <transition class="animate__animated " enter-active-class="animate__fadeInDown animate__fast"
            leave-active-class="animate__fadeOutUp animate__fast">
            <div class="weather-chart-content untouchable forbid-select" v-if="modelValue">
                <div style="position: absolute; top: 10px; left: 10px; width: 130px;" class="no-wrap">
                    {{ city?.city }}{{ city?.district }}
                </div>
                <el-icon class="_close" @click="closeWeatherChart" size="20">
                    <Close />
                </el-icon>
                <el-scrollbar class="full-percent">
                    <div style="width: 100%;font-size: 30px;text-align: center;">
                        {{ getWeatherData.current.temperature.value }}°
                    </div>

                    <div style="width: 100%;">
                        <span style="width:calc(100% / 3);display: inline-block;text-align: center">
                            <icon :class="`weather-icon-${dict[getWeatherData.current.weather].icon}`" size="25" />
                            <div>{{ dict[getWeatherData.current.weather].name }}</div>
                        </span>
                        <span style="width:calc(100% / 3);display: inline-block;">
                            <div style="height: 25px;">日出：{{ day[0].sunrise }}</div>
                            <div>日落：{{ day[0].sunset }}</div>
                        </span>
                        <span style="width:calc(100% / 3);display: inline-block;">
                            <div style="height: 25px;">
                                湿 度：{{ getWeatherData.current.humidity.value }}%
                            </div>
                            <div>
                                紫外线：{{ getWeatherData.current.uvIndex }} {{ uvIndex[getWeatherData.current.uvIndex] }}
                            </div>
                        </span>
                    </div>

                    <div style="height: 30px;margin: 5px;background: #d9d65f;border-radius: 3px;">
                        <el-scrollbar @touchstart.prevent="touchstartAlert" @touchmove.prevent="touchmoveAlert"
                            ref="alertScrollbarRef">
                            <div style="height: 30px;font-size: 14px;line-height: 30px;padding: 0 10px;text-align: center;"
                                v-for="item in alert" class="no-wrap">
                                {{ item.title }}
                            </div>

                        </el-scrollbar>
                    </div>

                    <div style="padding:10px">每小时预报</div>
                    <div
                        style="background: var(--weather-background);margin: 0 5px;padding: 5px 0;border-radius: 3px;overflow: hidden;">
                        <div class="weatherChartContent" style="-webkit-overflow-scrolling: touch;">
                            <el-scrollbar>
                                <div :style="`width:${mobile ? (50 * hour.length) + 'px' : '100%'}`">
                                    <span v-for="item in hour" class="weatherInfo hour-weather">
                                        <div>
                                            {{ item.hour }}时
                                        </div>
                                        <icon :class="`weather-icon-${item.weather.icon} day-weather`" size="25" />
                                        <div>
                                            {{ item.weather.name }}
                                        </div>
                                        <div>
                                            {{ item.temperature }}°
                                        </div>
                                    </span>
                                </div>
                            </el-scrollbar>
                        </div>
                    </div>

                    <div style="padding:10px">近15天预报</div>
                    <div class="weatherChart untouchable"
                        style="background: var(--weather-background);margin: 0 5px;padding: 5px 0;border-radius: 3px;overflow: hidden;">
                        <div class="weatherChartContent">
                            <el-scrollbar style="width: 100%;height: 100%;">
                                <div class="day_content">
                                    <span class="weatherInfo eday-weather" v-for="(item, index) in day" :key="index">
                                        <div>{{ item.date }}</div>
                                        <div>{{ item.week }}</div>
                                        <div>{{ item.weatherFrom }}</div>
                                        <icon :class="`weather-icon-${item.weatherFromIcon} day-weather`" size="25" />
                                        <div>{{ item.temperatureFrom }}</div>
                                    </span>
                                </div>
                                <div id="charts"
                                    :style="`width: ${totalWidth};height: 100px;background: transparent;`" />
                                <div class="day_content">
                                    <span class="weatherInfo eday-weather" v-for="(item, index) in day" :key="index">
                                        <div>{{ item.temperatureTo }}</div>
                                        <icon :class="`weather-icon-${item.weatherToIcon} day-weather`" size="25" />
                                        <div>{{ item.weatherTo }}</div>
                                    </span>
                                </div>
                            </el-scrollbar>
                        </div>
                    </div>
                </el-scrollbar>
            </div>
        </transition>
    </teleport>
</template>

<script setup>
import * as echarts from 'echarts'
import { useMainStore, storeToRefs } from '@/pinia'
import { Close } from '@element-plus/icons-vue'
import { mobile } from '@/utils/tools'

const uvIndex = {
    "0": "很弱",
    "1": "很弱",
    "2": "很弱",
    "3": "弱",
    "4": "弱",
    "5": "中等",
    "6": "中等",
    "7": "强",
    "8": "强",
    "9": "很强",
    "10": "很强",
}

const city = JSON.parse(sessionStorage.getItem("location") || "{}")?.ad_info
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(["update:modelValue"])

const closeWeatherChart = () => {
    emit("update:modelValue", false)
}

const days = 15
const oneDayWidth = 50
const totalWidth = mobile ? (days * oneDayWidth + "px") : "100%"
const clientWidth = "365px"

const { getWeatherData } = storeToRefs(useMainStore())
const weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
// 生成15天的日期
const day = computed(() => {
    const weather = getWeatherData.value.forecastDaily?.weather?.value
    const temperature = getWeatherData.value.forecastDaily?.temperature?.value
    return Object.keys(getWeatherData.value).length > 0 ? getWeatherData.value.forecastDaily.sunRiseSet.value.map((e, index) => {
        const dayWeather = weather[index]
        const dayTemperature = temperature[index]
        const date = new Date(e.from)
        return {
            date: date.format("M.D"), week: weeks[date.getDay()], weatherFrom: dict.value[dayWeather.from].name, weatherFromIcon: dict.value[dayWeather.from].icon,
            weatherTo: dict.value[dayWeather.to].name, weatherToIcon: dict.value[dayWeather.to].icon,
            temperatureFrom: dayTemperature.from, temperatureTo: dayTemperature.to, sunrise: new Date(e.from).format("HH:mm"),
            sunset: new Date(e.to).format("HH:mm")
        }
    }) : []
})

// 生成15天的日期
const hour = computed(() => {
    const weather = getWeatherData.value.forecastHourly?.weather?.value
    const temperature = getWeatherData.value.forecastHourly?.temperature?.value
    return Object.keys(getWeatherData.value).length > 0 ? getWeatherData.value.forecastHourly.wind.value.map((e, index) => {
        const hourWeather = weather[index]
        const date = new Date(e.datetime)
        return {
            hour: date.format("H"), weather: dict.value[hourWeather], temperature: temperature[index]
        }
    }) : []
})

const alert = computed(() => {
    const alerts = getWeatherData.value.alerts.map(e => { return { level: e.level, title: e.title, type: e.type, detail: e.detail, click: true } })
    alerts.push({ title: getWeatherData.value.minutely.precipitation.description, click: false })
    return alerts
})

const dict = computed(() => {
    return Object.keys(getWeatherData.value).length > 0 ? getWeatherData.value.dict : {}
})

const temperature = computed(() => {
    return getWeatherData.value.forecastDaily?.temperature?.value || []
})

const alertScrollbarRef = ref(null)
let offsetY = 0
let scrollAlert = false
const touchstartAlert = (e) => {
    offsetY = e.touches[0].pageY
    scrollAlert = true
}

const touchmoveAlert = (e) => {
    const deltaY = e.touches[0].pageY - offsetY
    if (Math.abs(deltaY) > 10 && scrollAlert) {
        alertScrollbarRef.value.setScrollTop(alertScrollbarRef.value.wrapRef.scrollTop - (deltaY / Math.abs(deltaY) * 30))
        scrollAlert = false
    }
}

const drawer = () => {
    var chartDom = document.getElementById('charts');
    var myChart = echarts.init(chartDom);
    var option;
    const maxTemperature = temperature.value.map(e => parseInt(e.from))
    const minTemperature = temperature.value.map(e => parseInt(e.to))
    option = {
        toolbox: {
            show: !mobile
        },
        xAxis: {
            type: 'category',
            boundaryGap: !mobile,
            axisLabel: {
                show: false
            },
            show: false,
            splitLine: { show: !mobile },
            axisLine: { show: false },
            axisTick: { show: false }
        },
        yAxis: {
            type: 'value',
            max: Math.max(...maxTemperature),
            min: Math.min(...minTemperature),
            axisLabel: {
                show: !mobile
            },
            splitLine: { show: !mobile }, //去除网格线
            show: false
        },
        series: [
            {
                name: 'Highest',
                type: 'line',
                smooth: 0.35,
                data: maxTemperature,
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(5, 115, 233, 0.3)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(5,114,233,0)'
                        }
                    ])
                }
            },
            {
                name: 'Lowest',
                type: 'line',
                data: minTemperature,
                smooth: 0.35,
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(5, 115, 233, 0.3)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(5,114,233,0)'
                        }
                    ])
                }
            }
        ],
        grid: {
            top: '10px', // 与容器顶部的距离
            bottom: '10px', // 与容器底部的距离
            left: mobile ? '25px' : "0",
            right: mobile ? '30px' : "0"
        }
    }
    option && myChart.setOption(option);
}

watch(() => props.modelValue, (show) => {
    if (show) {
        nextTick(() => {
            drawer()
        })
    }
})
</script>

<style>
.weather-chart-content {
    background: #fff;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    pointer-events: all;
    z-index: 9999;
    height: 100%;
    --weather-background: rgb(255 208 208 / 28%);
}

.weatherInfo {
    display: inline-block;
    text-align: center;
}

.mobile .hour-weather {
    width: 50px !important;
}

.hour-weather {
    width: calc(100% / 23);
}

.mobile .eday-weather {
    width: calc((100% - 55px) / 14);
}

.eday-weather {
    width: calc(100% / 15);
}

.mobile .day_content {
    padding: 0;
    width: 750px;
    position: relative
}

.weatherInfo :first-child {
    margin: 0;
}

.weatherInfo div,
.day-weather {
    margin-top: 10px;
}

.weatherChartContent {
    width: 100%;
    height: 100%;
}

.weatherChart .el-scrollbar {
    width: v-bind(clientWidth);
}

._close {
    position: absolute;
    top: 8px;
    right: 10px;
    z-index: 10;
    background: rgb(255 89 89 / 30%);
    border-radius: 50%;
    padding: 3px;
}

.weather-chart-content .el-scrollbar__bar.is-horizontal,
.weather-chart-content .el-scrollbar__bar.is-vertical {
    display: none !important;
}
</style>